import sys
from xml.sax import make_parser, handler
import mx, mx.DateTime

class XMLTV(handler.ContentHandler):

    def __init__(self):
    	self.channels = {}
	self.currentChannel = None
	self.inDisplay = False
	self.program = None # The program details as a dict
	self.programs = {} # Key is channel, ordered array of program dicts

    def startElement(self, name, attrs):
        self.buf = ''
        if (name == 'channel'):
            self.currentChannel = attrs['id']
        elif (name == 'display-name'):
            self.channels[self.currentChannel] = ''
	    self.inDisplay = True
	elif name == 'programme':
	    self.program = {}
	    self.program['channel'] = attrs['channel']
	    self.program['start'] = attrs['start']
	    self.program['stop'] = attrs['stop']

    def endElement(self, name):
        if (name == 'channel'):
	    self.currentChannel = None
	elif (name == 'display-name'):
	    self.channels[self.currentChannel] = self.buf
	    self.inDisplay = False
	elif name == 'programme':
	    if not self.programs.has_key(self.program['channel']):
	        self.programs[self.program['channel']] = []
	        
	    self.programs[self.program['channel']].append(self.program)
	    self.program = None
	elif name == 'title':
	    self.program['title'] = self.buf
	elif name == 'category':
	    self.program['category'] = self.buf
	elif name == 'desc':
	    self.program['desc'] = self.buf

    def characters(self, ch):
        self.buf += ch

    def endDocument(self):
        # sort the programs 
        for ch in c.programs:
            c.programs[ch].sort(self.sortProgram)
        return

    def sortProgram(self, a, b):
        ta = mx.DateTime.strptime(a['start'], "%Y%m%d%H%M%S %z")
        tb = mx.DateTime.strptime(b['start'], "%Y%m%d%H%M%S %z")
        return int((ta-tb).seconds)

    def __getitem__(self, key):
        """
        get method
        """
        return self.channels[key]

    def has_key(self, key):
        """
        has_key method
        """
        return self.channels.has_key(key)

    def keys(self):
        return self.channels.keys()

    def values(self):
        return self.channels.values()

    def parse(self, file):
        """
	Setup and do the parsing on this file
	"""
	parser = make_parser()
	parser.setContentHandler(self)
        parser.setFeature(handler.feature_validation, 0)
        parser.setFeature(handler.feature_namespaces, 0)
        parser.setFeature(handler.feature_external_pes, 0)
        parser.setFeature(handler.feature_external_ges, 0)
	parser.parse(file)


if __name__ == '__main__': 
    c = XMLTV()
    c.parse(sys.argv[1])
    for ch in c.channels:
        print ch, c.channels[ch]

    for ch in c.programs:
        for p in c.programs[ch]:
	    print p
